package com.example.qu_tao.View;

import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.R;
import com.example.qu_tao.adapter.ImageAdapter;
import com.example.qu_tao.database.DBHelper;

import org.jetbrains.annotations.Nullable;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class FaDongTaiActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_PICK = 1;
    private static final int MAX_IMAGE_COUNT = 9;
    private static final int MAX_CONTENT_LENGTH = 200;

    private EditText etContent;
    private TextView tvPublish;
    private RecyclerView rvImages;
    private ImageAdapter imageAdapter;
    private ArrayList<Uri> selectedImages = new ArrayList<>();
    private ImageView ivAddImage;
    private ImageButton btnBack; // 添加返回按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fadongtai);

        initView();
        initRecyclerView();
        initListeners();
    }

    private void initView() {
        etContent = findViewById(R.id.et_content);
        tvPublish = findViewById(R.id.tv_publish);
        rvImages = findViewById(R.id.rv_images);
        ivAddImage = findViewById(R.id.iv_add_image);
        btnBack = findViewById(R.id.btn_back); // 初始化返回按钮
    }

    private void initRecyclerView() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvImages.setLayoutManager(layoutManager);

        imageAdapter = new ImageAdapter(this, new ArrayList<Bitmap>());
        rvImages.setAdapter(imageAdapter);
    }

    private void initListeners() {
        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> showExitConfirmationDialog());
        // 发布按钮点击事件
        tvPublish.setOnClickListener(v -> {
            String content = etContent.getText().toString().trim();
            if (TextUtils.isEmpty(content) && selectedImages.isEmpty()) {
                Toast.makeText(this, "请输入内容或添加图片", Toast.LENGTH_SHORT).show();
                return;
            }

            if (content.length() > MAX_CONTENT_LENGTH) {
                Toast.makeText(this, "内容字数不能超过 " + MAX_CONTENT_LENGTH, Toast.LENGTH_SHORT).show();
                return;
            }

            publishDynamic(content);
        });

        // 添加图片按钮点击事件
        ivAddImage.setOnClickListener(v -> openImagePicker());

    }

    // 检查是否有未保存的更改
    private boolean hasUnsavedChanges() {
        return !TextUtils.isEmpty(etContent.getText().toString().trim()) || !selectedImages.isEmpty();
    }

    // 显示退出确认对话框
    private void showExitConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setMessage("是否放弃本次发布？")
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    finish();
                })
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .show();
    }


    // 处理系统返回键
    @Override
    public void onBackPressed() {
        if (hasUnsavedChanges()) {
            showExitConfirmationDialog();
        } else {
            super.onBackPressed();
        }
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_IMAGE_PICK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK) {
            if (data != null) {

                if (data.getClipData() != null) {
                    ClipData clipData = data.getClipData();
                    int itemCount = clipData.getItemCount();

                    for (int i = 0; i < itemCount; i++) {
                        if (selectedImages.size() >= MAX_IMAGE_COUNT) {
                            Toast.makeText(this, "最多只能选择 " + MAX_IMAGE_COUNT + " 张图片", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        Uri imageUri = clipData.getItemAt(i).getUri();
                        selectedImages.add(imageUri);
                    }
                } else if (data.getData() != null) {
                    if (selectedImages.size() >= MAX_IMAGE_COUNT) {
                        Toast.makeText(this, "最多只能选择 " + MAX_IMAGE_COUNT + " 张图片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    selectedImages.add(data.getData());
                }

                loadSelectedImages();
            }
        }
    }

    private void loadSelectedImages() {
        new Thread(() -> {
            List<Bitmap> bitmaps = new ArrayList<>();
            ContentResolver contentResolver = getContentResolver();

            for (Uri uri : selectedImages) {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;

                    InputStream inputStream = contentResolver.openInputStream(uri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
                    if (bitmap != null) {
                        bitmaps.add(bitmap);
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(this, "图片太大，请选择较小的图片", Toast.LENGTH_SHORT).show());
                }
            }

            runOnUiThread(() -> {
                imageAdapter.updateData(bitmaps);
            });
        }).start();
    }

    private void publishDynamic(String content) {
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
        int userId = 1;
        String username = "测试用户";

        new Thread(() -> {
            ContentResolver contentResolver = getContentResolver();
            SQLiteDatabase db = new DBHelper(this).getWritableDatabase();

            try {
                db.beginTransaction();

                ContentValues postValues = new ContentValues();
                postValues.put("user_id", userId);
                postValues.put("username", username);
                postValues.put("content", content);
                postValues.put("post_type", 0);
                postValues.put("create_time", currentTime);

                long postId = db.insert("posts", null, postValues);

                if (postId == -1) {
                    throw new Exception("插入帖子失败");
                }

                if (!selectedImages.isEmpty()) {
                    for (Uri imageUri : selectedImages) {
                        try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
                            byte[] imageData = outputStream.toByteArray();

                            ContentValues photoValues = new ContentValues();
                            photoValues.put("post_id", postId);
                            photoValues.put("image", imageData);

                            long photoId = db.insert("photo", null, photoValues);
                            if (photoId == -1) {
                                throw new Exception("插入图片失败");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                db.setTransactionSuccessful();

                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(this, "动态发布成功", Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK);
                    finish();

                    // 通知 QuTaoQuanFragment 和 WodeQutaoquanActivity 更新数据
                    Intent intent = new Intent("com.example.qu_tao.UPDATE_POSTS");
                    sendBroadcast(intent);
                });

            } catch (Exception e) {
                e.printStackTrace();
                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(this, "发布失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            } finally {
                db.endTransaction();
                db.close();
            }
        }).start();
    }
}